package com.barry.generator

import java.sql.DriverManager
import java.util.concurrent.ConcurrentHashMap

import org.slf4j.LoggerFactory

import scala.util.{Failure, Success, Try}

/**
  * 类功能描述：报表线程管理器
  *
  * @author WangXueXing create at 18-11-2 上午11:35
  * @version 1.0.0
  */
object ReportThreadManager {
  private val logger = LoggerFactory.getLogger(getClass)
  /**
    * 报表ID与对应线程map
    */
  val REPORT_THREAD_MAP: ConcurrentHashMap[Long, Thread] = new ConcurrentHashMap()

  /**
    * 将对应报表子线程放入线程池
    *
    * @param reportId 报表ID
    * @param thread 对应子线程
    */
  def put(reportId: Long, thread: Thread): Unit = {
    REPORT_THREAD_MAP.put(reportId, thread)
  }

  /**
    * 获取对应报表线程
    * @param reportId 报表ID
    * @return
    */
  def get(reportId: Long): Thread ={
    REPORT_THREAD_MAP.get(reportId)
  }

  /**
    * 将对应报表子线程移除线程池
    * @param reportId 报表ID
    */
  def remove(reportId: Long): Unit ={
    REPORT_THREAD_MAP.remove(reportId)
  }

  /**
    * 销毁指定报表子线程
    * @param reportId 报表ID
    */
  def deploy(reportId: Long)={
    val thread = REPORT_THREAD_MAP.get(reportId)
    if(thread != null){
      Try{
        if(!thread.isInterrupted){
          logger.info(s"线程:${reportId} 开始被结束")

          logger.info("before interrupt")
          thread.getStackTrace.foreach(println)

          thread.interrupt()

          Thread.sleep(10)
          logger.info("after interrupt")
          thread.getStackTrace.foreach(println)
        }
      } match {
        case Success(x) => logger.info(s"线程:${reportId} 被成功杀死")
        case Failure(e) => logger.error(s"线程:${reportId} interrupt 失败", e)
      }
      REPORT_THREAD_MAP.remove(reportId)
    }
  }

  val thread1 = new Thread(new Runnable {
    override def run(): Unit = {
      ReportThreadManager.deploy(1)
      println(s"thread 1 killed")
    }
  })

  def main(args: Array[String]): Unit = {
    Class.forName("org.apache.hive.jdbc.HiveDriver")
    val con = DriverManager.getConnection("jdbc:hive2://192.168.71.127:10000/finance", "goods", null)
    val stmt = con.createStatement
    var res = stmt.executeQuery("SELECT company_name,store_code,store_name,source_date,trade_type,trade_no,third_party_payment_no,business_type,cast(business_amount as decimal(20, 2)) business_amount,cast(service_charge as decimal(20, 4)) service_charge,trade_time,customer_account,updated_at,created_at FROM t_pay_source_data")
    while(res.next()){
      println(res.getString(1))
    }
  }
}
